package info.androidhive.slidingmenu;

import mindshare.Login;
import android.app.Activity;
import android.os.Bundle;

import static info.androidhive.slidingmenu.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static info.androidhive.slidingmenu.CommonUtilities.EXTRA_MESSAGE;
import static info.androidhive.slidingmenu.CommonUtilities.SENDER_ID;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gcm.GCMRegistrar;
public class Aux extends Activity {
	
	// label to display gcm messages
    TextView lblMessage;
     
    // Asyntask
    AsyncTask<Void, Void, Void> mRegisterTask;
     
    // Alert dialog manager
    AlertDialogManager alert = new AlertDialogManager();
     
    // Connection detector
    ConnectionDetector cd;
     
    public static String nickname;
    public static String register;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		/*
		setContentView(R.layout.activity_aux);

		if (savedInstanceState == null) {
			getFragmentManager().beginTransaction()
					.add(R.id.container, new PlaceholderFragment()).commit();
		}
		
		*/
		cd = new ConnectionDetector(getApplicationContext());
		 
        // Check if Internet present
        if (!cd.isConnectingToInternet()) {
            // Internet Connection is not present
            alert.showAlertDialog(Aux.this,
                    "Internet Connection Error",
                    "Please connect to working Internet connection", false);
            // stop executing code by return
            return;
        }
        Log.d("DEBUGEANDO", "EN ONCREATE 2");
        // Getting name, email from intent
        Intent i = getIntent();
         
        nickname = i.getStringExtra("nickname");
        register = i.getStringExtra("register");     
        Log.d("DEBUGEANDO", "name: "+nickname+" email: "+register);
        Log.d("DEBUGEANDO", "EN ONCREATE 3");
        // Make sure the device has the proper dependencies.
        GCMRegistrar.checkDevice(this);
        Log.d("DEBUGEANDO", "EN ONCREATE 4");
        // Make sure the manifest was properly set - comment out this line
        // while developing the app, then uncomment it when it's ready.
        GCMRegistrar.checkManifest(this);
        Log.d("DEBUGEANDO", "EN ONCREATE 5");
        //lblMessage = (TextView) findViewById(R.id.lblMessage);
        
        registerReceiver(mHandleMessageReceiver, new IntentFilter(
                DISPLAY_MESSAGE_ACTION));
         
        // Get GCM registration id
        final String regId = GCMRegistrar.getRegistrationId(this);
 
        // Check if regid already presents
        if (regId.equals("")) {
        	Log.d("DEBUGEANDO", "regid=nada");
            // Registration is not present, register now with GCM           
            GCMRegistrar.register(this, SENDER_ID);
            
            
        } else {
        	Log.d("DEBUGEANDO", "regid diferente");
            // Device is already registered on GCM
            if (GCMRegistrar.isRegisteredOnServer(this)) {
            	Log.d("DEBUGEANDO", "already registered");
                // Skips registration.              
                Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
                	Toast.makeText(getApplicationContext(), "En notificar",Toast.LENGTH_LONG).show();
                	//************************************************Intent o = new Intent(this, EnviadorNotificacion.class);
                	//startActivity(o);
                	
                	Log.d("DEBUGEANDO", "******ALREADY REGISTERED");
                	Intent o = new Intent(this, Login.class);
                	startActivity(o);
                
            } else {
            	Log.d("DEBUGEANDO", "Lo estoy registrando");
                // Try to register again, but not in the UI thread.
                // It's also necessary to cancel the thread onDestroy(),
                // hence the use of AsyncTask instead of a raw thread.
                final Context context = this;
                mRegisterTask = new AsyncTask<Void, Void, Void>() {
 
                    @Override
                    protected Void doInBackground(Void... params) {
                        // Register on our server
                        // On server creates a new user
                        ServerUtilities.register(context, nickname, register);
                        return null;
                    }
 
                    @Override
                    protected void onPostExecute(Void result) {
                        mRegisterTask = null;
                    }
 
                };
                mRegisterTask.execute(null, null, null);
                
                
            }
        }
        Log.d("DEBUGEANDO", "*****FINALIZANDO AUX");
        Intent o = new Intent(this, ProfileConfig.class);
        startActivity(o);
        this.finish();
	}
/*

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_aux, container,
					false);
			return rootView;
		}
	}
	*/
	private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
        	Log.d("DEBUGEANDO","LLEGUE A ONRECIEVE");
            String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
            // Waking up mobile if it is sleeping
            WakeLocker.acquire(getApplicationContext());
            //Log.d("DEBUGEANDO","**MSJ "+intent.getExtras().getString(EXTRA_MESSAGE));
             
            /**
             * Take appropriate action on this message
             * depending upon your app requirement
             * For now i am just displaying it on the screen
             * */
             
            // Showing received message
            //lblMessage.append(newMessage + "\n");           
            
            //Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();
//            Toast.makeText(getApplicationContext(), "En on recieve", Toast.LENGTH_LONG).show();
            
            // Releasing wake lock
            WakeLocker.release();
            finish();
        }
    };
     
    @Override
    protected void onDestroy() {
        if (mRegisterTask != null) {
            mRegisterTask.cancel(true);
        }
        
        try {
            unregisterReceiver(mHandleMessageReceiver);
            GCMRegistrar.onDestroy(this);
        } catch (Exception e) {
        	Log.d("DEBUGEANDO", "DESTRUIR REGISTRO =(");
            Log.e("UnRegister Receiver Error", "> " + e.getMessage());
        }
        super.onDestroy();
    }
 




}
